const basicUrl = "https://gateway.xiaohong.work/api/jijin"
// const basicUrl = "http://localhost:18888/jijin"


function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
}

// 请求失败错误处理中心
function requestFail (res) {
	var userinfo = uni.getStorageSync("userInfo")
	if(userinfo == ""){
		// 关闭所有页面跳转登录页面 同时关闭定时任务
		uni.reLaunch({
			url:'../addAndRegister/addAndRegister',
			animationType: 'pop-in',
			animationDuration: 200
		})
	}
	var access_token =uni.getStorageSync(userinfo.id+'_access_token')
	var token_type =uni.getStorageSync(userinfo.id+'_token_type')
	var refresh_token =uni.getStorageSync(userinfo.id+'_refresh_token')
	var expires_in =uni.getStorageSync(userinfo.id+'_expires_in')
	// 令牌失效错误
	if(res.statusCode == 401){
		if(res.data.error == 'invalid_token'){
			if(access_token && token_type && refresh_token && expires_in){
				// 令牌过期 刷新令牌
				uni.showToast({
					title:'令牌过期,正在刷新',
					icon:'none'
				});
				uni.request({
					url: basicUrl+'/oauth/user/refresh?',
					method: 'GET',
					data:{
						"refresh_token":refresh_token
					},
					success: function(res) {
						if(res.data.code === 20000){
							var tokenData = res.data.data.body
							console.log(tokenData)
							// 刷新令牌数据
							uni.setStorageSync(userinfo.id + "_access_token",tokenData.access_token)
							uni.setStorageSync(userinfo.id + "_token_type",tokenData.token_type)
							uni.setStorageSync(userinfo.id + "_refresh_token",tokenData.refresh_token)
							uni.setStorageSync(userinfo.id + "_expires_in",tokenData.expires_in)
						}else{
							if(res.data.code == 20005){
								// 刷新令牌已失效 重新登录
								console.log('刷新令牌已失效 重新登录')
								// 退出清除数据
								uni.removeStorageSync(userinfo.id + "_access_token")
								uni.removeStorageSync(userinfo.id + "_token_type")
								uni.removeStorageSync(userinfo.id + "_refresh_token")
								uni.removeStorageSync(userinfo.id + "_expires_in")
								var userList = uni.getStorageSync("userList")
								if(userList.length == 0){
									// 关闭所有页面跳转登录页面 同时关闭定时任务
									uni.reLaunch({
										url:'../addAndRegister/addAndRegister',
										animationType: 'pop-in',
										animationDuration: 200
									})
								}
								for (var i = 0; i < userList.length; i++) {
									if(userList[i].id === userinfo.id){
										// 删除
										userList.splice(i,1)
									}
								}
								this.userArray = userList
								uni.setStorageSync("userList",userList)
								uni.showToast({
									icon:'none',
									title:"刷新令牌已失效 重新登录"
								})
								// 关闭所有页面跳转登录页面 同时关闭定时任务
								uni.reLaunch({
									url:'../addAndRegister/addAndRegister',
									animationType: 'pop-in',
									animationDuration: 200
								})
								
							}
						}
					},
					fail: () => {
						uni.showModal({
							content: "网络错误！",
							showCancel: false
						});
					},
					complete() {
						// 停止当前页面下拉刷新
						// uni.hideLoading()
					}
				});
				
			}else{
				// 令牌无效 重新登录
				uni.showToast({
					icon:'none',
					title:"令牌无效 请重新登录"
				})
				uni.reLaunch({
					url:'../addAndRegister/addAndRegister',
					animationType: 'pop-in',
					animationDuration: 200
				})
			}
		}else{
			// 令牌无效 重新登录
			// 关闭所有页面跳转登录页面 同时关闭定时任务
			uni.showToast({
				icon:'none',
				title:"令牌无效 请重新登录"
			})
			uni.reLaunch({
				url:'../addAndRegister/addAndRegister',
				animationType: 'pop-in',
				animationDuration: 200
			})
		}
	}else if(res.statusCode == 404){
		uni.showToast({
			icon:"none",
			title:"未找到该服务请求！"
		})
	}else if(res.statusCode == 500){
		uni.showToast({
			icon:"none",
			title:"后台错误！"
		})
	}else if(res.statusCode == 502){
		uni.showToast({
			icon:"none",
			title:"后台服务未启动！"
		})
	}else if(res.statusCode == 503){
		uni.showToast({
			icon:"none",
			title:"后台服务未启动！"
		})
	}else if(res.statusCode == 444){
		// 限流
		uni.showToast({
			icon:"none",
			title: JSON.stringify(res.data)
		})
	}else{
		uni.showToast({
			icon:"none",
			title:"其他错误，错误内容："+ JSON.stringify(res.data.message)
		})
	}
	
}



module.exports = {
	formatTime,
	formatLocation,
	dateUtils,
	basicUrl,
	requestFail
}
